package com.yl.project.lvyou.spot.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.yl.common.utils.StringUtils;
import com.yl.common.utils.file.FileUploadUtils;
import com.yl.framework.config.YlConfig;
import com.yl.project.lvyou.video.domain.ScenicVideo;
import com.yl.project.lvyou.video.service.IScenicVideoService;
import com.yl.project.system.files.domain.UploadedFiles;
import com.yl.project.system.files.service.IUploadedFilesService;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.yl.framework.aspectj.lang.annotation.Log;
import com.yl.framework.aspectj.lang.enums.BusinessType;
import com.yl.project.lvyou.spot.domain.ScenicSpot;
import com.yl.project.lvyou.spot.service.IScenicSpotService;
import com.yl.framework.web.controller.BaseController;
import com.yl.framework.web.domain.AjaxResult;
import com.yl.common.utils.poi.ExcelUtil;
import com.yl.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 景区信息Controller
 * 
 * @author yl
 * @date 2025-03-11
 */
@Controller
@RequestMapping("/lvyou/spot")
public class ScenicSpotController extends BaseController
{
    private String prefix = "scenemanager/spot";

    @Autowired
    private IScenicSpotService scenicSpotService;

    @Autowired
    private IUploadedFilesService uploadedFilesService;

    @Autowired
    private IScenicVideoService scenicVideoService;

    @RequiresPermissions("scenemanager:spot:view")
    @GetMapping()
    public String spot()
    {
        return prefix + "/spot";
    }

    /**
     * 查询景区信息列表
     */
    @RequiresPermissions("scenemanager:spot:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ScenicSpot scenicSpot)
    {
        startPage();
        List<ScenicSpot> list = scenicSpotService.selectScenicSpotList(scenicSpot);
        return getDataTable(list);
    }

    /**
     * 导出景区信息列表
     */
    @RequiresPermissions("scenemanager:spot:export")
    @Log(title = "景区信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ScenicSpot scenicSpot)
    {
        List<ScenicSpot> list = scenicSpotService.selectScenicSpotList(scenicSpot);
        ExcelUtil<ScenicSpot> util = new ExcelUtil<ScenicSpot>(ScenicSpot.class);
        return util.exportExcel(list, "spot");
    }

    /**
     * 新增景区信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存景区信息
     */
    @RequiresPermissions("scenemanager:spot:add")
    @Log(title = "景区信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ScenicSpot scenicSpot)
    {

        return toAjax(scenicSpotService.insertScenicSpot(scenicSpot));

    }

    /**
     * 修改景区信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ScenicSpot scenicSpot = scenicSpotService.selectScenicSpotById(id);
        mmap.put("scenicSpot", scenicSpot);
        return prefix + "/edit";
    }

    /**
     * 修改保存景区信息
     */
    @RequiresPermissions("scenemanager:spot:edit")
    @Log(title = "景区信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ScenicSpot scenicSpot)
    {
        return toAjax(scenicSpotService.updateScenicSpot(scenicSpot));
    }

    /**
     * 删除景区信息
     */
    @RequiresPermissions("scenemanager:spot:remove")
    @Log(title = "景区信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(scenicSpotService.deleteScenicSpotByIds(ids));
    }

    /**
     * 跳转到上传页面页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/uploadImg/{id}")
    public String uploadImg(@PathVariable("id")Long id,ModelMap model){
        model.put("id", id);
        return prefix+"/uploadImg";
    }

    @GetMapping("/uploadTupian")
    public String uploadTupian(ModelMap model){
        return prefix+"/uploadTupian";
    }
    @GetMapping("/uploadVideo/{id}")
    public String uploadVideo(@PathVariable("id")Long id,ModelMap model){
        model.put("id", id);
        return prefix+"/uploadVideo";
    }
    @GetMapping("/lookJingqutupian/{id}")
    public String lookJingqutupian(@PathVariable("id")Long id,ModelMap model){
        model.put("id", id);
        return prefix+"/lookJingqu";
    }

    @GetMapping("/lookVideo/{id}")
    public String lookVideo(@PathVariable("id")Long id,ModelMap model){
        model.put("id", id);
        return prefix+"/lookVideo";
    }

    @PostMapping("/lookVideolist")
    @ResponseBody
    public TableDataInfo lookVideolist(Long id){
        ScenicVideo scenicVideo= new ScenicVideo();
        scenicVideo.setScenicId(id);
        startPage();
        List<ScenicVideo> list = scenicVideoService.select(scenicVideo);
        return getDataTable(list);
    }


    @PostMapping("/lookTupianlist")
    @ResponseBody
    public TableDataInfo lookTupianlist(Long id){
        UploadedFiles uploadedFiles= new UploadedFiles();
        uploadedFiles.setYewuId(id);
        uploadedFiles.setYewuName("SPOT");
        startPage();
        List<UploadedFiles> list = uploadedFilesService.select(uploadedFiles);
        return getDataTable(list);
    }


    @PostMapping("/addPic")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("myFile") MultipartFile file) throws IOException {
        try
        {
            if (!file.isEmpty())
            {
                String spotPic = FileUploadUtils.upload(YlConfig.getAvatarPath(), file);
                return AjaxResult.success(spotPic);
            }
            return error();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }

    }

    @PostMapping("/uploadJingquPic")
    @ResponseBody
    public AjaxResult tianjiajiaocai(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam(value = "id", required = true) Long id,
                                     @RequestParam(value = "imgIndex", required = true) Integer imgIndex,
                                     MultipartFile myFile){
        MultipartFile file = myFile;
        Map<String,Object> map = new HashMap<>();
        map.put("id", id);
        UploadedFiles files = new UploadedFiles();
        files.setCreateBy(getUserId().toString());;
        files.setYewuId(id);

        int res = 0;
        int count = uploadedFilesService.selectCount(files)+1;

        if (!file.isEmpty()) {
            try {
                String uploadFilePath = file.getOriginalFilename();
                // 截取上传文件的文件名
                String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,
                        uploadFilePath.indexOf('.'));

                // 截取上传文件的后缀
                String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.lastIndexOf("."));

                String fileName = UUID.randomUUID().toString();


                String path = YlConfig.getUploadPath();
                File file1 = new File(path);
                long size = FileUtils.sizeOf(file1);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                file.transferTo(new File(path + fileName + uploadFileSuffix));
                files.setFileName(uploadFileName);
                files.setFilePath(fileName + uploadFileSuffix);
                files.setFileType(uploadFileSuffix);
                files.setFileSize(size);
                files.setYewuName("SPOT");
                files.setXuhao(count+imgIndex);
                res= uploadedFilesService.insertUploadedFiles(files);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return toAjax(false);
        }
        if(res >0){
            return toAjax(true);
        }else{
            return toAjax(false);
        }
    }

    /**
     * 上传导览视频
     * @param request
     * @param response
     * @param id
     * @param myFile
     * @return
     */
    @PostMapping("/uploadVideoSave")
    @ResponseBody
    public AjaxResult uploadVideoSave(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam(value = "id", required = true) Long id,
                                     MultipartFile myFile){
        MultipartFile file = myFile;
        Map<String,Object> map = new HashMap<>();
        map.put("id", id);
        ScenicVideo scenicVideo = scenicVideoService.selectScenicVideoById(id);
        if(scenicVideo !=null){
            return AjaxResult.error("文件已上传");

        }
        ScenicVideo video = new ScenicVideo();
        video.setScenicId(id);

        int res = 0;
        int count = scenicVideoService.selectCount(video)+1;
        if (!file.isEmpty()) {
            try {
                String uploadFilePath = file.getOriginalFilename();
                // 截取上传文件的文件名
                String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,
                        uploadFilePath.indexOf('.'));

                // 截取上传文件的后缀
                String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.lastIndexOf("."));

                String fileName = UUID.randomUUID().toString();


                String path = YlConfig.getUploadPath();
                File file1 = new File(path);
                long size = FileUtils.sizeOf(file1);
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                file.transferTo(new File(path + fileName + uploadFileSuffix));
                video.setVideoTitle(uploadFileName+uploadFileSuffix);
                video.setVideoUrl(fileName);
                res= scenicVideoService.insertScenicVideo(video);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return toAjax(false);
        }
        if(res >0){
            return toAjax(true);
        }else{
            return toAjax(false);
        }
    }

    @PostMapping("/isCove")
    @ResponseBody
    public AjaxResult isCove(Long id,Integer isBanner)
    {
        ScenicSpot scenicSpot= new ScenicSpot();
        scenicSpot.setId(id);
        scenicSpot.setIsBanner(isBanner);
        scenicSpotService.updateScenicSpot(scenicSpot);
        return success();
    }

    /**
     * 跳转景区坐标点选择
     * @return
     */
    @GetMapping("/selectCoordinate")
    public String selectCoordinate(String coordinate,ModelMap model){
        if(StringUtils.isNotEmpty(coordinate)){
            model.put("coordinate",coordinate);
        }else{
            model.put("coordinate","");
        }
        return prefix+"/coordinate";
    }

    /**
     * 删除图片 removeTupian
     */
    @PostMapping( "/removeTupian")
    @ResponseBody
    public AjaxResult removeTupian(String ids)
    {
        return toAjax(uploadedFilesService.deleteUploadedFilesByIds(ids)
        );
    }


    /**
     * 删除图片 音频
     */
    @PostMapping( "/removeVideo")
    @ResponseBody
    public AjaxResult removeVideo(String ids)
    {
        return toAjax(scenicVideoService.deleteScenicVideoByIds(ids));
    }


    @PostMapping( "/tongji")
    @ResponseBody
    public AjaxResult tongji(ScenicSpot scenicSpot)
    {
        return AjaxResult.success(scenicSpotService.selectScenicSpotListTj(scenicSpot));
    }

}
